package com.wang.interview.threads;

import java.util.concurrent.Semaphore;

/**
 * @author: wang
 * @date: 2021/7/24 21:02
 * @description: Semaphore类似 抢车位，车位就这么多谁抢到谁用，直到某个放开，其余在获取之前被阻塞
 */
public class SemaphoreTest {
    static int j = 6;

    public static void sub(){
        System.out.println(--j);
    }
    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(3);


        for ( int i = 1 ; i <= 6 ; i++ ){
            final int temp = i;
            new Thread(()->{
                try {
                    semaphore.acquire();
                    System.out.println(Thread.currentThread().getName()+"starting");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                sub();
                System.out.println(Thread.currentThread().getName()+"finished");
                semaphore.release();
            },temp+" : ").start();
        }
    }
}
